import { ElMessage } from "element-plus";
import api from "@/api";

/**
 * 获取url参数
 * @param name key名
 */
export function getUrlKey(name: string): string {
	return decodeURIComponent(
		(new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
			location.href
		) || [, ""])[1].replace(/\+/g, "%20")
	);
}

/**
 * Token
 */
interface Token {
	token: string;
	expired_time: number;
}
const token_key = `token`;
// 获取有效token
export const getToken = () => {
	const tokenStr = window.localStorage.getItem(token_key);
	if (tokenStr) {
		const token: Token = JSON.parse(tokenStr);

		// 判断token是否过期
		if (token.expired_time > Math.floor(new Date().getTime() / 1000)) {
			return token.token;
		} else {
			window.localStorage.removeItem(token_key);
		}
	}
	return null;
};
// 设置token
export const setToken = (token: string) => {
	window.localStorage.setItem(
		token_key,
		JSON.stringify({
			token,
			expired_time: Math.floor(new Date().getTime() / 1000) + 24 * 60 * 60,
		})
	);
};
// 移除token
export const removeToken = () => {
	window.localStorage.removeItem(token_key);
};

/**
 * 验证手机号
 * @param phone
 * @returns
 */
export function validatePhoneNumber(phone: string) {
	const regex = /^1[3-9]\d{9}$/;
	return regex.test(phone);
}

/**
 * 上传附件
 */
interface UploadFile {
	ext?: string[]; // 允许上传的文件格式
	size?: number; // 允许上传的文件大小(mb)
	onConfirm(url: string): void;
}
export interface File {
	extension: string;
	file_name: string;
	file_url: string;
	id: string;
	size: number;
	create_date: string;
	type: number; // 文件类型 1=>图片 2=>文档 3=>音视频 4=>压缩包 5=>其他
}
export const uploadFile = (props: UploadFile) => {
	const input = document.createElement("input");
	input.type = "file";
	input.accept = "";

	input.addEventListener("change", async (event: any) => {
		const file = event.target.files[0];

		// 验证文件格式
		const ext = file.name.split(".").pop().toLowerCase();
		if (props.ext && !props.ext.includes(ext)) {
			ElMessage.warning("请上传正确格式的文件");
			return;
		}

		// 验证文件大小
		if (props.size && file.size > (props?.size || 5) * 1024 * 1024) {
			ElMessage.warning(`文件大小不能超过 ${props.size}MB`);
			return;
		}

		// 上传文件
		const params = new FormData();
		params.append("file", file);
		params.append("dirCode", "1000");

		const msg = await api.system.uploadFile(params);
		if (msg.code == 1000) {
			props.onConfirm(msg.data);
		}

		input.remove();
	});

	input.click();
};
